// pages/cleanRecordInsert/cleanRecordInsert.js
const httprequest = require('../../utils/http_utils.js')
const dateutil = require('../../utils/date_util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    cleanOptions: [],
    cleanitems: [{
        name: '是',
        value: '1'
      },
      {
        name: '否',
        value: '0'
      },
    ], //保洁项
    cleanresultitems: [{
        name: '已完成',
        value: '1',
        checked: true
      },
      {
        name: '未完成',
        value: '0'
      },
    ], //保洁结果
    picnum: 0, //已上传图片数量
    description: '', //问题描述
    cleanresult: '1', //保洁结果是否异常
    FileGuid: "",
    imgs: [],
    RoomRowGuid: '', //扫码获得的保洁房间唯一标识
    TaskGuid: '', //任务唯一标识
    imgs2: [], //用于过渡图片地址和rowguid关系
    CleanDetail: [], //保洁项结果集合
    info: '',
    error: '',
    isfree:false, //是否自由选择
    // isDisabled:false, //是否禁用
  },

  //保洁项是否异常选择
  cleanOptionsChange: function(e) {
    console.log(e.currentTarget.dataset.rowguid, e.currentTarget.dataset.option, e.detail.value)
    var newarr = this.data.CleanDetail
    var param = {
      RowGuid: e.currentTarget.dataset.rowguid,
      ItemTypeValue: e.detail.value
    }
    for (var i = 0; i < newarr.length; i++) {
      if (newarr[i].RowGuid == param.RowGuid) {
        newarr.splice(i, 1)
      }
    }
    newarr.push(param)
    // console.log(newarr)
    this.setData({
      CleanDetail: newarr
    })
    var a = this.data.cleanresultitems
    let count = 0;
    newarr.map(ele => {
      if (ele.ItemTypeValue == 0) {
        count = count + 1;
      } else {
        // console.log("11111111")
      }
      console.log(count+'----------计数')
      this.countnum(count);
    })
  },

  countnum(count) {

    // if (this.data.isfree == true){
    //   return
    // }else{
      var a = this.data.cleanresultitems
      if (count == 0) {
        a[0].checked = true
        a[1].checked = false
        this.setData({
          resultchecked: true,
          cleanresultitems: a,
          cleanresult: '1'
        })
      } else {
        a[0].checked = false
        a[1].checked = true
        this.setData({
          resultchecked: false,
          cleanresultitems: a,
          cleanresult: '0'
        })
      }
    // }
  },

  //自由选择保洁结果
  freeChoice:function(e){
    var that = this;
    // console.log(JSON.stringify(e.detail.value))
    console.log(JSON.stringify(e))
    that.setData({
      cleanresult: e.detail.value,
      // isfree:true
    })
  },

  //保洁项文本和数字输入
  option_input(e) {
    let detail = this.data.CleanDetail
    let param = {
      RowGuid: e.currentTarget.dataset.rowguid,
      ItemTypeValue: e.detail.value
    }
    for (var i = 0; i < detail.length; i++) {
      if (detail[i].RowGuid == e.currentTarget.dataset.rowguid) {
        detail.splice(i, 1)
      }
    }
    detail.push(param)
    this.setData({
      CleanDetail: detail
    })
    // console.log(this.data.CleanDetail)
  },

  textareaChange: function(e) {
    this.setData({
      description: e.detail.value
    })
  },

  //选择图片
  chooseimage: function() {
    var that = this
    var newImgs = that.data.imgs
    var imgs_2 = that.data.imgs2
    wx.chooseImage({
      count: 9 - that.data.imgs.length,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        for (var i = 0; i < tempFilePaths.length; i++) {
          newImgs.push(tempFilePaths[i])
        }
        for (var i = 0; i < tempFilePaths.length; i++) {
          let path = tempFilePaths[i]
          //压缩图片
          wx.compressImage({
            src: tempFilePaths[i],
            quality: 80,
            success: function(res) {
              console.log(res)
              var tempimgpath = res.tempFilePath
              const uploadFile = wx.uploadFile({
                url: httprequest.host + httprequest.apiInfo.MultipleFileUploadMobileApi,
                filePath: tempimgpath,
                name: dateutil.getNowTime(),
                header: {
                  "Content-Type": "multipart/form-data"
                },
                formData: {
                  FileType: '保洁记录'
                },
                success: function(res) {
                  var param1 = {
                    path: path,
                    path2: tempimgpath,
                    RowGuid: JSON.parse(res.data).RowGuid,
                    FileGuid: JSON.parse(res.data).FileGuid
                  }
                  imgs_2.push(param1)
                },
                fail: function(err) {
                  that.setData({
                    error: '图片上传失败'
                  })
                  console.error(err)
                }
              })
              uploadFile.onProgressUpdate((res) => {
                if (res.progress == 100) {
                  wx.hideLoading()
                } else {
                  wx.showLoading({
                    title: '图片已上传' + res.progress + '%',
                  })
                }
              })
            },
            fail: function(err) {
              console.error(('压缩图片失败', err))
            }
          })
        }
        that.setData({
          imgs: newImgs,
          imgs2: imgs_2,
          picnum: that.data.imgs.length,
        })
        console.log('imgs---', that.data.imgs)
        console.log('imgs2---', that.data.imgs2)
        if (that.data.picnum >= 5) {
          that.setData({
            paddingbottom_height: 400
          })
        } else {
          that.setData({
            paddingbottom_height: 250
          })
        }
      }
    })
  },

  //删除图片
  deleteImg: function(e) {
    var that = this;
    console.log(e.currentTarget.dataset.index + "___________下标显示")
    wx.showModal({
      title: '删除图片',
      content: '确定删除图片',
      confirmText: '删除',
      success: function(res) {
        if (res.confirm) {
          let index = e.currentTarget.dataset.index;
          let imgs = that.data.imgs;
          let imgs_2 = that.data.imgs2;
          let filepath = e.currentTarget.dataset.filepath
          for (var i = 0; i < imgs_2.length; i++) {
            if (imgs_2[i].path == filepath) {
              var param = {
                RowGuid: imgs_2[i].RowGuid
              }
              httprequest.GetValidateRequest(httprequest.apiInfo.MultipleFileDeleteMobileApi, param,
                function(res) {
                  console.log('删除的结果---', res)
                },
                function(err) {
                  console.error(err)
                })
              imgs_2.splice(i, 1)
            }
          }
          imgs.splice(index, 1)
          that.setData({
            imgs: imgs,
            picnum: that.data.imgs.length,
            imgs2: imgs_2
          })
          if (that.data.picnum >= 5) {
            that.setData({
              paddingbottom_height: 400
            })
          } else {
            that.setData({

              paddingbottom_height: 250
            })
          }
        }
      }
    })
  },

  //提交
  submit() {
    var that = this
    console.log(that.data.cleanOptions.length, that.data.CleanDetail.length)
    if (that.data.cleanOptions.length != that.data.CleanDetail.length) {
      that.setData({
        info: '请检查保洁项是否有遗漏'
      })
      return
    }
    for (var i = 0; i < that.data.CleanDetail.length; i++) {
      if (that.data.CleanDetail[i].ItemTypeValue == '' || that.data.CleanDetail[i].ItemTypeValue == null) {
        that.setData({
          info: '请检查保洁项是否有遗漏'
        })
        break
        return
      }
    }
    var imgs2 = that.data.imgs2
    var temp = that.data.FileGuid
    if (imgs2.length > 0) {
      for (var i = 0; i < imgs2.length; i++) {
        temp += imgs2[i].RowGuid + ','
      }
      temp = temp.substring(0, temp.lastIndexOf(','))
      that.setData({
        FileGuid: temp
      })
      // console.log('FileGuid------', that.data.FileGuid)
    }
    if (that.data.FileGuid == null || that.data.FileGuid == undefined || that.data.FileGuid.length == 0) {
      that.setData({
        info: '请上传图片！'
      })
      return
    }
    var param = {
      RowGuid: that.data.TaskGuid,
      CleanStatus: that.data.cleanresult, //0  1
      CleanRemarks: that.data.description, //问题反馈
      FileGuid: that.data.FileGuid,
      Details: that.data.CleanDetail //保洁详情  
    }
    console.log('提交参数'+ JSON.stringify(param))
    httprequest.PostValidateRequest(httprequest.apiInfo.AddCleanRecordApi, param,
      function(res) {
        // console.log(res, typeof(res), res == "0");
        if (res == "0") {
          that.setData({
            success: '提交成功'
          })
          setTimeout(function() {
            wx.navigateBack();
          }, 1500)
        } else {
          that.setData({
            error: '提交失败'
          })
        }
      },
      function(err) {
        console.error(err)
        that.setData({
          error: '提交失败'
        })
      }
    )
  },

  //获取保洁任务详情
  GetCleanTaskDetailsByRoomID() {
    // console.log('获取保洁任务详情')
    var that = this
    var param = {
      RoomRowGuid: that.data.RoomRowGuid
    }
    httprequest.GetValidateRequest(httprequest.apiInfo.GetCleanTaskDetailsByRoomIDApi, param,
      function(res) {
        console.log(JSON.stringify(res))
        if (res != null && res.TaskGuid != '') {
          that.setData({
            TaskGuid: res.TaskGuid, //任务唯一标识
            title: res.RoomName, //设置保洁详情页标题为房间名称
            cleanOptions: res.Detaildt.DetailData,
            // isDisabled: true
          })
          // console.log('cleanOptions', that.data.cleanOptions)
        } else {
          that.setData({
            info: '当前房间暂无保洁任务',
          })
          setTimeout(function() {
            wx.navigateBack();
          }, 1500)
        }
      },
      function(err) {
        console.error(err)
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.RoomRowGuid != undefined && options.RoomRowGuid != '') {
      console.log('options.RoomRowGuid', options.RoomRowGuid)
      //根据房间唯一表示获取保洁项
      this.setData({
        RoomRowGuid: options.RoomRowGuid
      })
    }
    this.GetCleanTaskDetailsByRoomID();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})